<?php


namespace app\service;


use app\entity\SysUserEntity;
use app\exception\ErrorCode;
use app\exception\OaException;
use app\models\request\ReqLogin;
use app\models\request\ReqUserList;
use app\models\request\ReqUserUpdate;
use app\models\response\RespLogin;
use app\models\response\RespUserDetail;
use app\models\response\RespUserList;
use app\models\UserDto;
use app\utils\JwtUtil;
use yii\data\Pagination;

class UserService
{
    /**
     * @param $username
     * @param $password
     * @return array|\yii\db\ActiveRecord|SysUserEntity
     * @throws OaException
     */
    public function findByUserNameAndPassword($username,$password) {
        $userEntity = SysUserEntity::find()->where(["username"=>$username,"password"=>$password])->one();
        if(!$userEntity) {
            throw new OaException(ErrorCode::USER_NOT_FOUND);
        }
        return $userEntity;
    }

    public function queryAllPermsSql($userId,$super) {

        if ($super == false) {

            $sql = "select m.url as perms  from sys_user_role ur
        LEFT JOIN sys_role_menu rm on ur.role_id = rm.role_id
        LEFT JOIN sys_menu m on rm.menu_id = m.menu_id
        where  ur.user_id=".$userId;
        } else {
            $sql = "select url as perms from sys_menu  ";
        }
        return SysUserEntity::getDb()->createCommand($sql)->queryAll();
    }


    /**
     * @param $userId
     * @return array|null
     */
    public function queryAllPerms($userId) {
        $service = new SysUserRoleService();
        $arr = $service->queryRoleIdList($userId);
        $super = false;
        foreach ($arr as $e) {
            if ($e->getRoleId() == 1) {
                $super = true;break;
            }
        }
        $res =  $this->queryAllPermsSql($userId,$super);
        if (!$res) return null;
        $arr = [];
        foreach ($res as $detail) {
            $arr[] = $detail["perms"];
        }
        return $arr;
    }

    /**
     * @param ReqLogin $req
     * @return RespLogin
     * @throws OaException
     */
    public function login(ReqLogin $req) {
        $resp = new RespLogin();
        $entity = $this->findByUserNameAndPassword($req->getUsername(),$req->getPassword());
        $userInfo = new UserDto();
        $userInfo->setId($entity->getUserId());
        $userInfo->setRealname($entity->getUsername());
        $allPerms = $this->queryAllPerms($entity->getUserId());
        $userInfo->setPerms(array_unique($allPerms));
        $time = time(); //当前时间
        $token = [
            'iss' => '', //签发者 可选
            'aud' => '', //接收该JWT的一方，可选
            'iat' => $time, //签发时间
            'nbf' => $time , //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time+3600*12, //过期时间,这里设置2个小时
            'data' => $userInfo
        ];

        $code = JwtUtil::encode($token, \Yii::$app->params["jwtKey"]);
        $resp->setUserInfo($userInfo);
        $resp->setAuthorization($code);
        return $resp;
    }

    public function queryPage(ReqUserList $req) {
        $data = SysUserEntity::find()->orderBy("create_time asc");
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => $req->getPageSize(),'page'=>$req->getPageNum()-1]);
        /**@var $entities SysUserEntity[]*/
        $entities = $data->offset($pages->getOffset())->limit($pages->getLimit())->all();
        $list = [];
        $service = new SysUserRoleService();
        $arr=[];
        foreach ($entities as $detail) {
            $r = new RespUserDetail();
            $r->setUserId($detail->getUserId());
            $r->setUsername($detail->getUsername());
            $r->setEmail($detail->getEmail());
            $r->setMobile($detail->getMobile());
            $r->setStatus($detail->getStatus());
            $r->setPassword($detail->getPassword());
            $r->setCreateUserId($detail->getCreateUserId());
            $r->setCreateTime($detail->getCreateTime());
            $r->setSysRoleDTOList($service->queryRoleIdList($r->getUserId()));
            $arr[] = $r;
        }
        $resp = new RespUserList();
        $resp->setPageSize($req->getPageSize());
        $resp->setList($arr);
        $resp->setTotal(intval($pages->totalCount));
        $resp->setPageNum($req->getPageNum());
        return $resp;
    }

    public function delete($userId) {
        SysUserEntity::deleteAll("user_id=".$userId);
        return true;
    }

    public function update(ReqUserUpdate $req) {



        if ($req->getUserId()) {
            $entity = SysUserEntity::find()->where(["user_id"=>$req->getUserId()])->one();
        } else {
            $entity = new SysUserEntity();
        }



        $entity->setUsername($req->getUsername());
        $entity->setCreateUserId($req->getCreateUserId());
        $entity->setStatus($req->getStatus());
        $entity->setPassword($req->getPassword());
        $entity->setEmail($req->getEmail());
        $entity->setMobile($req->getMobile());
        $entity->save();
        return $entity->primaryKey;

    }
}